public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val = val;
        }
    }
    public TreeNode root = null;

    //查找
    public TreeNode search(int val){
        TreeNode cur = root;
        while(cur != null){
            if(val < cur.val){
                cur = cur.left;
            }else if(val > cur.val){
                cur = cur.right;
            }else{
                return cur;
            }
        }
        return null;
    }

    //插入
    public void insert(int val){
        TreeNode node = new TreeNode(val);
        if(root == null){
            root = node;
            return ;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(val < cur.val){
                parent = cur;
                cur = cur.left;
            }else if(val > cur.val){
                parent = cur;
                cur = cur.right;
            }else{
                return;
            }
        }
        if(parent.val > val){
            parent.left = node;
        }else{
            parent.right = node;
        }
    }

    //删除
    public void remove(int val){
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(val < cur.val){
                parent = cur;
                cur = cur.left;
            }else if(val > cur.val){
                parent = cur;
                cur = cur.right;
            }else{
                //删除
                removeNode(cur,parent);
                return;
            }
        }
    }
    private void removeNode(TreeNode cur,TreeNode parent){
        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(cur == parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            TreeNode target = cur.left;
            TreeNode targetP = cur;
            while(target.right != null){
                targetP = target;
                target = target.right;
            }
            cur.val = target.val;
            if(targetP.right == target){
                targetP.right = target.left;
            }else{
                targetP.left = target.left;
            }
        }
    }
}
